//
//  TeachingWebViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "TeachingWebViewController.h"
#import "AppDelegate.h"
#import "CollectHandler.h"
#import "TeachCol.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
@interface TeachingWebViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIView *menuV;
@property (nonatomic, strong) UIImageView *menuCornerIV;
@property (nonatomic, strong) UIButton *menuBtn;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UIButton *backB;
@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation TeachingWebViewController


- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appD.leftSlideVC setPanEnabled:NO];
        self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
        _HUD.labelText = @"数据加载中...";
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Screenheight )];
    webView.delegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.teachingData.content_url]];
    [self.view addSubview:webView];
    [webView loadRequest:request];
    
    for (id subview in webView.subviews)
        if ([[subview class] isSubclassOfClass: [UIScrollView class]])
            ((UIScrollView *)subview).bounces = NO;
    
    self.menuV = [[UIView alloc] init];
    self.menuV.frame = CGRectMake(ScreenWidth - 120, 18 + 64, 110, 60);
    self.menuV.layer.cornerRadius = 10;
    self.menuV.backgroundColor = [UIColor whiteColor];
    
    self.menuCornerIV = [[UIImageView alloc] init];
    self.menuCornerIV.image = [[UIImage imageNamed:@"picture2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.menuCornerIV.frame = CGRectMake(ScreenWidth - 45, 64, 20, 20);
    self.menuV.hidden = YES;
    self.menuCornerIV.hidden = YES;
    
    
    UIImage *imageM = [[UIImage imageNamed:@"picture.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.menuBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_menuBtn setImage:imageM forState:UIControlStateNormal];
    _menuBtn.frame = CGRectMake(0, 0, 20, 20);
    [_menuBtn addTarget:self action:@selector(menuAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_menuBtn];
    _menuBtn.hidden = NO;
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake(10, 0, 90, self.menuV.bounds.size.height / 2-1);
    [button1 setTitleColor:[UIColor blackColor] forState:normal];
    [self.menuV addSubview:button1];
    [button1 setTitle:@"分享" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];

    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake(10, self.menuV.bounds.size.height / 2 , 90, self.menuV.bounds.size.height/ 2 - 1);
    [self.menuV addSubview:self.button];
    [self.button setTitleColor:[UIColor blackColor] forState:normal];
    
    [self.button addTarget:self action:@selector(button12Action:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.menuV];
    [self.view addSubview:self.menuCornerIV];
    
    UIView *upV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    upV.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.139 alpha:1.000];
    [self.view addSubview:upV];
    
    // 返回按钮
    self.backB = [UIButton buttonWithType:UIButtonTypeSystem];
    _backB.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.139 alpha:1.000];
    _backB.frame = CGRectMake(10, 20, 40, 40);
    _backB.layer.cornerRadius = 20;
    UIImage *backI = [[UIImage imageNamed:@"picture1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [_backB setImage:backI forState:UIControlStateNormal];
    [_backB setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [_backB addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backB];
    if (self.isPresent) {
        _backB.hidden = NO;
    }else{
        _backB.hidden = YES;
    }
    

    
}

#pragma mark 分享
- (void)button1Action:(UIButton *)btn
{
    self.menuV.hidden = YES;

    NSString *urlString = self.teachingData.cover_image_url;
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"分享:<%@>%@",self.teachingData.title,[NSURL URLWithString:self.teachingData.content_url]]
                                     images:@[image]
                                        url:[NSURL URLWithString:self.teachingData.content_url]
                                      title:@"分享标题"
                                       type:SSDKContentTypeImage];
    [ShareSDK showShareActionSheet:nil
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@", error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       default:
                           break;
                   }
                   
                   
               }];
    
}

- (void)backAction:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)menuAction:(UIButton *)btn
{
    CollectHandler *collecthandler = [CollectHandler instandDefault];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"TeachCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"title contains '%@'",self.teachingData.title]];
    
    NSArray *arr = [collecthandler.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count == 0) {
        [self.button setTitle:@"收藏" forState:UIControlStateNormal];
    } else {
        [self.button setTitle:@"取消收藏" forState:UIControlStateNormal];
        
    }
    
    if (self.menuV.hidden) {
        self.menuV.hidden = NO;
        self.menuCornerIV.hidden = NO;
    }else{
        self.menuV.hidden = YES;
        self.menuCornerIV.hidden = YES;
    }
    
}

#pragma mark 收藏方法
- (void)button12Action:(UIBarButtonItem *)btn
{
    CollectHandler *collecthandler = [CollectHandler instandDefault];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"TeachCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"title contains '%@'",self.teachingData.title]];
    NSArray *arr = [collecthandler.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count == 0) {
        self.menuV.hidden = YES;
        [self.button setTitle:@"取消收藏" forState:UIControlStateNormal];
        TeachCol *teachCol = [NSEntityDescription insertNewObjectForEntityForName:@"TeachCol" inManagedObjectContext:collecthandler.managedObjectContext];
        teachCol.title = self.teachingData.title;
        teachCol.content_url = self.teachingData.content_url;
        teachCol.cover_image_url = self.teachingData.cover_image_url;
        [collecthandler saveContext];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        [self presentViewController:alertVC animated:YES completion:^{
        }];
    } else {
        self.menuV.hidden = YES;
        [self.button setTitle:@"收藏" forState:UIControlStateNormal];
        TeachCol *teachFetch = [arr lastObject];
        [collecthandler.managedObjectContext deleteObject:teachFetch];
        [collecthandler saveContext];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"取消收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        [self presentViewController:alertVC animated:YES completion:^{
        }];
    }
    
    
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.HUD removeFromSuperview];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
